﻿using Infrastructure.Attribute;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using ZR.DataCollection.ICommunication;
using ZR.DataCollection.SingleParameter;

namespace ZR.DataCollection.Communication
{
    [AppService(ServiceType = typeof(ICommPlcExtend), ServiceLifetime = LifeTime.Singleton)]
    public class CommPlcExtend : ICommPlcExtend
    {
        public event Action<string, INormCommunication, int, string, object>? CommunicationDataCallback;

        private Dictionary<string, (INormCommunication Communication, Action<int, string, object> Handler)> stationCommunicationMap = new Dictionary<string, (INormCommunication, Action<int, string, object>)>();

        public void Initialize()
        {
            foreach (var opComm in CurrentAppInfo.Current.communicationPairs)
            {
                Action<int, string, object> handler = (itemNo, address, value) =>
                {
                    CommunicationDefault_plc_dataChange(opComm.Key, opComm.Value, itemNo, address, value);
                };
                stationCommunicationMap[opComm.Key] = (opComm.Value, handler);
                opComm.Value.plc_dataChange += handler;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="stationCode">工作站编号</param>
        /// <param name="plc">plc对象</param>
        /// <param name="itemNo">点位序号</param>
        /// <param name="address">点位地址</param>
        /// <param name="positionValue">点位值</param>
        private void CommunicationDefault_plc_dataChange(string stationCode, INormCommunication plc, int itemNo, string address, object positionValue)
        {
            CommunicationDataCallback?.Invoke(stationCode, plc, itemNo, address, positionValue);
        }
    }
}